/**
 @Name：layuiAdmin iframe版主入口
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
 */

document.domain = 'xiujiadian.com';

layui.extend({
    setter: 'config', //配置模块
    admin: 'lib/admin', //核心模块
    view: 'lib/view', //视图渲染模块
    // $api: '{/}/static/js/module/api/zmn.api',
    zmnUtils: 'lib/extend/zmnUtils'
}).define(['setter', 'admin', 'zmnUtils'], function(exports) {
    var setter = layui.setter,
        element = layui.element,
        admin = layui.admin,
        tabsPage = admin.tabsPage,
        view = layui.view,
        layer = layui.layer,
        zmnUtils = layui.zmnUtils,
        //打开标签页
        openTabsPage = function(url, text) {
            //遍历页签选项卡
            var matchTo, tabs = $('#LAY_app_tabsheader>li'),
                path = url.replace(/(^http(s*):)|(\?[\s\S]*$)/g, '');

            if (setter.whiteListOfMultiTab.includes(url)) {
                let params = zmnUtils.getQueryParams(url);
                params.t = Date.now();
                url = zmnUtils.serializeURL(url, params);
            }
            console.log(tabs)
            tabs.each(function(index) {
                var li = $(this),
                    layid = li.attr('lay-id');

                if (layid === url) {
                    matchTo = true;
                    tabsPage.index = index;
                }
            });
            text = text || '新标签页';

            if (setter.pageTabs) {
                //如果未在选项卡中匹配到，则追加选项卡
                if (!matchTo) {
                    $(APP_BODY).append([
                        '<div class="layadmin-tabsbody-item layui-show">', '<iframe src="' + url + '" frameborder="0" class="layadmin-iframe"></iframe>', '</div>'
                    ].join(''));
                    tabsPage.index = tabs.length;
                    element.tabAdd(FILTER_TAB_TBAS, {
                        title: '<span>' + text + '</span>',
                        id: url,
                        attr: path
                    });
                } else {
                    var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
                    var params = zmnUtils.getQueryParams(url);
                    params.t = Date.now();
                    iframe[0].contentWindow.location.href = zmnUtils.serializeURL(url.split('?')[0], params);
                }
            } else {
                var iframe = admin.tabsBody(admin.tabsPage.index).find('.layadmin-iframe');
                iframe[0].contentWindow.location.href = url;
            }

            //定位当前tabs
            element.tabChange(FILTER_TAB_TBAS, url);
            admin.tabsBodyChange(tabsPage.index, {
                url: url,
                text: text
            });
        }

    , APP_BODY = '#LAY_app_body', FILTER_TAB_TBAS = 'layadmin-layout-tabs', $ = layui.$, $win = $(window);

    // window.$http = layui.$http;
    // window.$api = layui.$api;
    window.zmnEnv = (function() {
        var host = location.host;
        if (/:/.test(host)) {
            return zmnEnum.ENV_TYPE.dev;
        } else if (/test-/.test(host)) {
            return zmnEnum.ENV_TYPE.test;
        } else if (/test2-/.test(host)) {
            return zmnEnum.ENV_TYPE.test2;
        } else if (/uat-/.test(host)) {
            return zmnEnum.ENV_TYPE.uat;
        } else if (/pre-/.test(host)) {
            return zmnEnum.ENV_TYPE.pre;
        } else {
            return zmnEnum.ENV_TYPE.prod;
        }
    })();

    // 设置 $.ajax 公用方案
    (function ajaxSetup() {
        $.ajaxSetup({
            timeout: 20000
        });
    })();

    //初始
    if (admin.screen() < 2) admin.sideFlexible();

    //将模块根路径设置为 controller 目录
    layui.config({
        //base: setter.base + 'modules/'
        base: '/static/js/module/'
    });

    //扩展 lib 目录下的其它模块
    layui.each(setter.extend, function(index, item) {
        var mods = {};
        mods[item] = '{/}' + setter.base + 'lib/extend/' + item;
        layui.extend(mods);
    });

    // 扩展其他自定义
    if (setter.otherExtend) {
        layui.extend(setter.otherExtend);
    }

    view().autoRender();

    //加载公共模块
    layui.use('zmn.common');

    //对外输出
    exports('index', {
        openTabsPage: openTabsPage
    });

    /**
     * 消息通知
     *
     * crossDomain: 跨域
     * xhrFields: 带 Cookie
     */
    function readMsg() {
        $.ajax({
            type: "GET",
            url: "https://api-push.xiujiadian.com/push/inner/getOne",
            crossDomain: true,
            dataType: 'json',
            xhrFields: { withCredentials: true },
            async: false,
            timeout: 1000,
            success: function(data) {
                if (data.statusBool) {
                    open(data.data);
                } else {
                    setTimeout(readMsg, waitTime);
                }
            }
        });
    }

    function open(inner) {
        var businessData = JSON.parse(inner.businessData);
        var btn = "<a lay-href='url'>【name】</a>";

        if (businessData != null) {
            var url = businessData.linkUrl;
            var name = businessData.linkName;

            btn = btn.replace("url", url);
            btn = btn.replace("name", name == null ? "查看" : name);
        } else {
            btn = "";
        }

        top.layer.open({
            id: 'PUSH_MSG',
            title: '信息',
            content: inner.content + btn,
            shade: 0,
            offset: 'rb',
            btn: ['已读', '暂存'],
            yes: function(index, layero) {
                read(inner.id);
                setTimeout(readMsg, waitTime);
                layer.close(index);
            },
            btn2: function(index, layero) {
                setTimeout(readMsg, waitTime + addTime);
                layer.close(index);
            },
            cancel: function(index) {
                setTimeout(readMsg, waitTime + addTime);
                layer.close(index);
            }
        });
    }

    function read(id) {
        $.ajax({
            type: "GET",
            url: "https://api-push.xiujiadian.com/push/inner/read?id=" + id,
            crossDomain: true,
            dataType: 'json',
            xhrFields: { withCredentials: true },
            async: false
        });
    }

    var waitTime = 10 * 1000;
    var addTime = 60 * 1000;
    // TODO 暂时取消通知
    // readMsg();
});